//
//  DetailRemindMeViewController.m
//  忘不了
//
//  Created by rimi on 16/7/16.
//  Copyright © 2016年 handuan. All rights reserved.
//

#import "DetailRemindMeViewController.h"
#import "SDAutoLayout.h"
#import "DetailRemindMeTableViewCell.h"
#import "TitleViewController.h"
#import "ContentViewController.h"
@interface DetailRemindMeViewController ()<UITableViewDelegate,UITableViewDataSource,TitleViewControllerDelegate,ContentViewControllerDelegate>

//@property (nonatomic,strong) UIView *dateView;
@property (nonatomic,strong) NSMutableDictionary *dic;
@property (nonatomic,assign) double timeNumber;
@property (nonatomic,strong) NSString *pickerDate;
@property (nonatomic,strong) UIButton *back;
@property (nonatomic,strong) UIImageView *bgImageView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *headingArray;
@property (nonatomic,strong) NSArray *contentArray;
@property (nonatomic,strong) NSString *titleString;
@property (nonatomic,strong) NSString *contentString;
@property (nonatomic,strong) NSString *musicString;
@property (nonatomic,strong) NSArray *titleArr;


@end

@implementation DetailRemindMeViewController

- (void)viewDidLoad {
    NSLog(@"%ld",(long)self.number);
    self.title = @"添加";
    [super viewDidLoad];
    [self loadUI];
}

- (void)loadUI{
    self.titleArr = @[@"标题",@"内容",@"铃声"];
    self.dic = @{@"heading":@"标题",@"content":@"内容",@"铃声":@"铃声"}.mutableCopy;
    self.dic1 = self.dic1.mutableCopy;
    NSLog(@"%@",self.dic1);
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(doneItemPressed)];
    self.navigationItem.rightBarButtonItem = doneItem;
    
    _bgImageView = [[UIImageView alloc]init];
    [_bgImageView setImage:[UIImage imageNamed:@"s"]];
    [self.view addSubview:_bgImageView];
    _bgImageView.sd_layout.topSpaceToView(self.view,0).leftSpaceToView(self.view,0).rightSpaceToView(self.view,0).bottomSpaceToView(self.view,0);
    
    
    UIDatePicker *oneDatePicker = [[UIDatePicker alloc] init];
    oneDatePicker.frame = CGRectMake(0, 0, 300, 200);
    if (_dic1 != nil) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"MM-dd HH:mm"];
        oneDatePicker.date = [formatter dateFromString:_dic1[@"data"]];
        NSLog(@"%@",_dic1[@"data"]);
    }else{
        oneDatePicker.date = [NSDate date];//设置初始时间
    }
    
    [oneDatePicker setDate:[NSDate dateWithTimeIntervalSinceNow:0] animated:YES];//设置时间，有动画效果   48*20*18
    oneDatePicker.timeZone = [NSTimeZone timeZoneWithName:@"GTM+8"];//设置时区，中国在东八区
    oneDatePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:0];//设置最小时间
    //72*60*60*-1
    oneDatePicker.datePickerMode = UIDatePickerModeDateAndTime;//设置样式
//    [oneDatePicker setValue:[UIColor whiteColor] forKey:@"textColor"];
    [oneDatePicker addTarget:self action:@selector(oneDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:oneDatePicker];
    oneDatePicker.sd_layout.topSpaceToView(self.view,84).leftSpaceToView(self.view,20).rightSpaceToView(self.view,20).heightIs(200);
    
    _tableView = [[UITableView alloc]init];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 70;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
    _tableView.sd_layout.topSpaceToView(self.view,350).rightSpaceToView(self.view,0).leftSpaceToView(self.view,0).bottomSpaceToView(self.view,0);
}
- (void)application {
    //添加本地通知
    NSDate * date = [NSDate dateWithTimeIntervalSinceNow:_timeNumber];
    
    [self _addLocalNotification:date];
}

#pragma mark - 添加本地通知
- (void) _addLocalNotification:(NSDate *) date{
    
    UILocalNotification * localNotification=[[UILocalNotification alloc] init];
    //设置开始时间
    localNotification.fireDate = date;
    
    //设置body
    if (_dic1 != nil) {
        localNotification.alertBody = self.dic1[@"heading"];
    }else{
        localNotification.alertBody = self.dic[@"heading"];
    }
    
    //设置action
    localNotification.alertAction = @"查看";
    
    //设置右上角数字
    localNotification.applicationIconBadgeNumber +=  1;
    
    //是否弹出提示框
    localNotification.hasAction = YES;
    
    //提示声音
    
    localNotification.soundName = UILocalNotificationDefaultSoundName;
    
    //如果想将通知的信息传递过去,必须使用userInfo属性
    if (_dic1 != nil) {
        localNotification.userInfo = @{@"message" : self.dic1[@"heading"],@"alarmID":self.dic1[@"data"],@"content":self.dic1[@"content"]};
    }else{
        localNotification.userInfo = @{@"message" : self.dic[@"heading"],@"alarmID":self.pickerDate,@"content":self.dic[@"content"]};
    }
    
    //设置闹铃
    localNotification.soundName = @"";
    
    //warning 注册完之后如果不删除，下次会继续存在，即使从模拟器卸载掉也会保留
    //注册通知  将本地通知加入本地通知调度池
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    
}



#pragma mark -- TitleViewControllerDelegate
- (void)addTitle:(NSString *)title {
    NSLog(@"%@",title);
    if (self.dic1 == nil) {
        [self.dic setValue:title forKey:@"heading"];
    }else{
        [self.dic1 setValue:title forKey:@"heading"];
    }
    [self.dic setObject:@"" forKey:@"image"];
    [self.tableView reloadData];
    
}

#pragma mark -- ContentViewControllerDelegate
- (void)addContent:(NSString *)content{
    if (self.dic1 == nil) {
        [self.dic setObject:content forKey:@"content"];
    }else{
        [self.dic1 setObject:content forKey:@"content"];
    }
    [self.dic setObject:@"" forKey:@"image"];
    [self.tableView reloadData];

}

#pragma mark -- UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifer = @"DetailRemindMeTableViewCell";
    DetailRemindMeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    if (!cell) {
        cell = [[DetailRemindMeTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifer];
    }
    
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.backgroundColor = [UIColor clearColor];
    cell.headingLabel.text = self.titleArr[indexPath.row];
    if (_dic1 != nil) {
        NSLog(@"%@",_dic1);
        if (indexPath.row == 0) {
            cell.contentLabel.text = _dic1[@"heading"];
        }
        if (indexPath.row == 1) {
            cell.contentLabel.text = _dic1[@"content"];
        }
        if (indexPath.row == 2) {
            cell.contentLabel.text = @"默认";
        }
    }else{
        if (self.dic.count == 0) {
            if (indexPath.row == 0) {
                cell.contentLabel.text = @"标题";
            }
            if (indexPath.row == 1) {
                cell.contentLabel.text = @"内容";
            }
            if (indexPath.row == 2) {
                cell.contentLabel.text = @"铃声";
            }

        }else{
            if (indexPath.row == 0) {
                cell.contentLabel.text = self.dic[@"heading"];
            }
            if (indexPath.row == 1) {
                cell.contentLabel.text = self.dic[@"content"];
            }
            if (indexPath.row == 2) {
                cell.contentLabel.text = @"铃声";
            }

        }
    }
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中颜色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == 0) {
        TitleViewController *titleViewController = [[TitleViewController alloc]init];
        if (_dic1 != nil) {
            titleViewController.titleString = _dic1[@"heading"];
        }else{
            titleViewController.titleString = self.dic[@"heading"];
        }
        titleViewController.delegate = self;
        [self.navigationController pushViewController:titleViewController animated:YES];
    }
    if (indexPath.row == 1) {
        ContentViewController *contentViewController = [[ContentViewController alloc]init];
        if (_dic1 != nil){
            contentViewController.contentString = _dic1[@"content"];
        
        }else{
            contentViewController.contentString = self.dic[@"content"];
            }
        
        contentViewController.delegate = self;
        [self.navigationController pushViewController:contentViewController animated:YES];
    }
    
    
    
}

#pragma mark -- Action

- (void)doneItemPressed{
    NSLog(@"%@",_pickerDate);
    NSLog(@"%@",self.dataSource);
    BOOL flag = YES;
    for (NSInteger index= 0; index < self.dataSource.count; index ++) {
        if ([_pickerDate isEqualToString:self.dataSource[index][@"data"] ]) {
            [self alertAction:@"请选择与当前不同的时间"];
            flag = NO;
            break;
        }
    }
    if (flag) {
        if (_pickerDate == nil) {
            [self alertAction:@"请选取之后的日期。"];
            
        }else{
            NSLog(@"%@",_pickerDate);
            if (self.dataSource.count == 0) {
                [self.dic setValue:_pickerDate forKey:@"data"];
                [self.dic setValue:@"" forKey:@"image"];
                [[NSUserDefaults standardUserDefaults] setValue:@[self.dic].mutableCopy forKey:@"rememberList"];
            }else{
                NSLog(@"%@",self.dic1[@"data"]);
                
                NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
                NSLog(@"%@",notificationArray);
                for (UILocalNotification *notif in notificationArray) {
                    if ([self.dateString isEqualToString:notif.userInfo[@"alarmID"]]) {
                        [[UIApplication sharedApplication] cancelLocalNotification:notif];
                        break;
                    }
                }
                
                [self.dic1 setValue:_pickerDate forKey:@"data"];
                [self.dic1 setValue:@"" forKey:@"image"];
                NSLog(@"%@",self.dic1[@"data"]);
                [self.dic setValue:_pickerDate forKey:@"data"];
                [self.dic setValue:@"" forKey:@"image"];
                if (self.number >= 0) {
                    self.dataSource[self.number] = self.dic1;
                }else{
                    [self.dataSource addObject:self.dic];
                }
                [[NSUserDefaults standardUserDefaults] setValue:self.dataSource.mutableCopy forKey:@"rememberList"];
            }
            
            [self application];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}

- (void)alertAction:(NSString *)string{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:sureAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)oneDatePickerValueChanged:(UIDatePicker *) sender {
    NSDateFormatter *selectDateFormatter = [[NSDateFormatter alloc] init];
    //    selectDateFormatter.dateFormat = @"yy:MM:dd"; //设置时间和日期的格式
    [selectDateFormatter setDateFormat:@"MM-dd H:mm"];
    NSLog(@"%@", [sender date]);
    NSString *date = [selectDateFormatter stringFromDate:[sender date]];
    if (_dic1 != nil) {
//        for (NSInteger index= 0; index < self.dataSource.count; index ++) {
//            if ([date isEqualToString:self.dataSource[index][@"data"] ]) {
//                [self alertAction:@"该时间已选过，请选择其他时间。"];
//                break;
//            }else {
                [_dic1 setObject:date forKey:@"data"];
//            }
//        }
    }else{
//        for (NSInteger index= 0; index < self.dataSource.count; index ++) {
//            if ([date isEqualToString:self.dataSource[index][@"data"] ]) {
//                [self alertAction:@"该时间已选过，请选择其他时间。"];
//                break;
//            }else {
                [self.dic setObject:date forKey:@"data"];
//            }
//        }
        
        
    }
        _pickerDate = date;
        NSLog(@"%@",_pickerDate);
    
    _timeNumber = [[sender date] timeIntervalSinceDate:[NSDate date]];
}

@end
